package com.bringspring.oauth.config.jwt;

import com.bringspring.common.base.UserInfo;
import com.bringspring.common.model.login.BaseSystemInfo;
import com.bringspring.common.util.UserProvider;
import com.bringspring.system.base.service.LogService;
import com.bringspring.oauth.service.LoginService;
import com.bringspring.system.base.service.SysConfigService;
import com.bringspring.system.permission.entity.UserEntity;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.token.TokenEnhancer;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * 根据需要配置Jwt内容增强器
 * @version V1.0.0
 * @copyright 股份有限公司
 * @author 开发平台组
 * @date 2021/3/16
 */
@Component
public class JwtTokenEnhancer implements TokenEnhancer {

    @Autowired
    private LogService logService;
    @Autowired
    private UserProvider userProvider;
    @Autowired
    private SysConfigService sysConfigService;

    @Autowired
    private LoginService loginService;

    @SneakyThrows
    @Override
    public OAuth2AccessToken enhance(OAuth2AccessToken oAuth2AccessToken, OAuth2Authentication oAuth2Authentication) {
        // 得到系统配置
        String account = oAuth2Authentication.getPrincipal().toString();
        //超级管理员模拟账户登录
        if(account.endsWith("@admin")){
            account = account.replace("@admin", "");
        }
        UserEntity existUser = loginService.isExistUser(account);
        BaseSystemInfo systemInfo = sysConfigService.getSysInfo();
        UserInfo userInfo = loginService.loginProcess(existUser);
        //创建map，将需要增加的内容放置到map中
        Map<String,Object> map = new HashMap<>(16);
        map.put("token",userInfo.getId());
        map.put("singleLogin", systemInfo.getSingleLogin());
        //写入日志
        logService.writeLogAsync(userInfo.getUserId(),userInfo.getRealName()+"/"+userInfo.getUserAccount(),"登录成功");

        ((DefaultOAuth2AccessToken)oAuth2AccessToken).setAdditionalInformation(map);
        return oAuth2AccessToken;
    }
}
